package com.jin.webvideo.base.util;

import java.util.Arrays;

public class ByteArray {
    private byte[] bs;
    private int length;
    private int capacity;
    private int expandSize;
    public ByteArray(){
        this(1024);
    }
    public ByteArray(byte[] bs){
        this(bs, 1024);
    }
    public ByteArray(int expandSize){
        this(new byte[expandSize], expandSize);
    }
    public ByteArray(byte[] bs, int expandSize){
        this.bs = bs;
        this.expandSize = expandSize;
    }
    public void append(byte append){
        int remaining = this.length + 1 - this.capacity;
        if (0 < remaining) {
            bs = expand(bs, this.expandSize);
            this.capacity = this.capacity + this.expandSize;
        }
        bs[length++] = append;
    }
    public void append(byte[] append){
        append(append, 0, append.length);
    }
    public void append(byte[] append, int start, int length){
        // 超出的大小
        int remaining = this.length + length - this.capacity;
        if (0 < remaining) {
            // 计算倍数
            int mult = (int) Math.ceil(remaining / (double)this.expandSize);
            // 扩展数组
            bs = expand(bs, mult * this.expandSize);
            // 更新最大容量
            this.capacity = this.capacity + mult * this.expandSize;
        }
        // 内容更新
        System.arraycopy(append, start, bs, this.length, length);
        // 更新长度
        this.length = this.length + length;
    }
    public byte[] toArray(){
        return Arrays.copyOfRange(bs, 0, length);
    }
    public ByteArray reverse() {
        ByteArray byteArray = new ByteArray(new byte[this.length], this.expandSize);
        for (int i = 0; i < this.length; i++) {
            byteArray.append(this.bs[this.length - i - 1]);
        }
        return byteArray;
    }
    public int getLength() {
        return length;
    }

    /**
     * 扩展数组大小
     * @param bs 原数组
     * @param length 需要新增的长度
     * @return
     */
    private static byte[] expand(byte[] bs, int length){
        byte[] rst = new byte[bs.length + length];
        System.arraycopy(bs, 0, rst, 0, bs.length);
        return rst;
    }

}
